<?php

namespace Lib;

final class Queue {

    /**
     * 压入队列
     *
     * @param string $name
     * @param array  $data
     *
     * @return boolean
     */
    public static function push($name, array $data) {
        $key   = sprintf(\Lib\Consts::QUEUE, $name);
        $redis = \Yaf\Registry::get('redis');

        $redis->rPush($key, \json_encode($data));
        $redis->expire($key, \Lib\Consts::EXPIRE_7DAY);

        return true;
    }

    /**
     * 弹出队列
     *
     * @param string $name
     * @return array
     */
    public static function pop($name) {
        $key    = sprintf(\Lib\Consts::QUEUE, $name);
        $json   = \Yaf\Registry::get('redis')->blPop($key, 10);
        $result = [];

        if(!empty($json[1])) {
            $data   = \json_decode($json[1], true);
            $result = (JSON_ERROR_NONE === json_last_error() ? $data : []);
        }

        return $result;
    }
}

